package com.cicadamob.contact.api.Utils.Data.File;




import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.os.Environment;
import android.text.TextUtils;

import com.cicadamob.contact.api.Utils.ContactConfig;
import com.cicadamob.contact.api.Utils.DateUtil;
import com.cicadamob.contact.api.Utils.FileUtils;
import com.cicadamob.contact.api.Utils.Utility;
import com.cicadamob.contact.api.Utils.Logger.AppLogger;


/**
 * FileManager
 *
 * author: yeyue
 *         14-9-15
 */
@SuppressLint("NewApi")
public class FileManager {

    private static final String PICTURE_CACHE = "picture_cache";

    private static final String TXT2PIC = "txt2pic";


    private static final String LOG = "log";
    
    private static final String ERROR="error";

    private static final String ECONTACT = "kakaonew";

    /**
     * install kakaonew, open app and login in, Android system will create cache dir.
     * then open cache dir (/sdcard dir/Android/data/com.gmccgz.kakaonew) with Root Explorer,
     * uninstall kakaonew and reinstall it, the new kakaonew app will have the bug it can't
     * read cache dir again, so I have to tell user to delete that cache dir
     */
    private static volatile boolean cantReadBecauseOfAndroidBugPermissionProblem = false;

    public static String getSdCardCachePath( ) {
        if (isExternalStorageMounted()) {
            File path = ContactConfig.getContext().getExternalCacheDir();
            if (path != null) {
                return path.getAbsolutePath();
            } else {
                if (!cantReadBecauseOfAndroidBugPermissionProblem) {
                    cantReadBecauseOfAndroidBugPermissionProblem = true;
//                    final Activity activity = GlobalContext.getInstance().getActivity();
//                    if (activity == null || activity.isFinishing()) {
//                        ToastUtils.show(GlobalContext.getInstance(),"出现异常");
//
//
//
//                        return "";
//                    }
//                    activity.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
////                          弹出对话框提示用户安装内存卡
//                            ToastUtils.show(GlobalContext.getInstance(),"无内存卡");
//
//                        }
//                    });
                }
            }
        } else {
            return "";
        }

        return "";
    }

    /** getCacheDataPath
     * @return
     */
    public static String getDataCachePath() {

        File path = ContactConfig.getContext().getCacheDir();
        return path.getAbsolutePath();
    }

    public File getAlbumStorageDir(String albumName) {

        File file = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), albumName);
        if (!file.mkdirs()) {
            AppLogger.e("Directory not created");
        }
        return file;
    }

    public static boolean isExternalStorageMounted() {

        boolean canRead = Environment.getExternalStorageDirectory().canRead();
        boolean onlyRead = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED_READ_ONLY);
        boolean unMounted = Environment.getExternalStorageState().equals(
                Environment.MEDIA_UNMOUNTED);

        return !(!canRead || onlyRead || unMounted);
    }






    public static String getLogDir() {
        String path = null;
        if (!isExternalStorageMounted()) {
            path = getDataCachePath() + File.separator + LOG;
        } else {
            path = getSdCardCachePath() + File.separator + LOG;
        }
        if (!new File(path).exists()) {
            new File(path).mkdirs();
        }
        return path;
    }
    public static String getErrorDir() {
        String path = null;
        if (!isExternalStorageMounted()) {
            path = getDataCachePath() + File.separator + ERROR;
        } else {
            path = getSdCardCachePath() + File.separator + ERROR;
        }
        if (!new File(path).exists()) {
            new File(path).mkdirs();
        }
        return path;
    }

    /**
     * 把日志文件写到硬盘
     *
     * @param fileName
     * @param logmessage
     */
    public static void createLogtoFile(String fileName, String logmessage) {

        try {
//            // 创建log文件
            File file = new File(getLogDir(), fileName);
            if (!file.exists()) {

                file.createNewFile();

            }
            String date = DateUtil.getCurrentTime();
            StringBuffer buffer = new StringBuffer();
            buffer.append("------------------------------------华丽分割线------------------------------  \r\n");
            buffer.append("[" + date + "] Pid:" + android.os.Process.myPid() + " Tid:" + android.os.Process.myTid() + " \r\n");
            buffer.append(logmessage + " \r\n");
            String message = buffer.toString();

            FileUtils.writeFile(file, new ByteArrayInputStream(message.getBytes("UTF-8")), true);

//			}

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 把日志文件写到硬盘
     *
     * @param fileName
     * @param logmessage
     */
    public static void createLogtoFile( String logmessage) {

        try {
//            // 创建log文件
         String fileName =  DateUtil.getCurrentTime()+".txt";
            File file = new File(getLogDir(), fileName);
            if (!file.exists()) {

                file.createNewFile();

            }
            String date = DateUtil.getCurrentTime();
            StringBuffer buffer = new StringBuffer();
            buffer.append("[" + date + "] Pid:" + android.os.Process.myPid() + " Tid:" + android.os.Process.myTid() + " \r\n");
            buffer.append(logmessage + " \r\n");
            String message = buffer.toString();

            FileUtils.writeFile(file, new ByteArrayInputStream(message.getBytes("UTF-8")), true);

//			}

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static String getTxt2picPath() {
        if (!isExternalStorageMounted()) {
            return "";
        }

        String path = getSdCardCachePath() + File.separator + TXT2PIC;
        File file = new File(path);
        if (file.exists()) {
            file.mkdirs();
        }
        return path;
    }

    /** createNewFile
     * @param absolutePath
     * @return
     */
public static File createNewFile(String absolutePath){
    if (TextUtils.isEmpty(absolutePath)) {
        return null;
    }

    File file = new File(absolutePath);
    if (file.exists()) {
        return file;
    } else {
        File dir = file.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            if (file.createNewFile()) {
                return file;
            }
        } catch (IOException e) {
            AppLogger.d(e.getMessage());
            return null;

        }

    }
    return null;
}

    /** createNewFileInSDCard
     * @param absolutePath
     * @return
     */
    public static File createNewFileInSDCard(String absolutePath) {
        if (!isExternalStorageMounted()) {
            AppLogger.e("sdcard unavailiable");
            return null;
        }

    return     createNewFile(absolutePath);

    }



    public static String getCacheSize() {
        if (isExternalStorageMounted()) {
            String path = getSdCardCachePath() + File.separator;
            FileSize size = new FileSize(new File(path));
            return size.toString();
        }
        return "0MB";
    }


    public static List<String> getCachePath() {
        List<String> path = new ArrayList<String>();
        if (isExternalStorageMounted()) {
            String thumbnailPath = getSdCardCachePath() + File.separator + PICTURE_CACHE;

            path.add(thumbnailPath);

        }
        return path;
    }

    public static String getPictureCacheSize() {
        long size = 0L;
        if (isExternalStorageMounted()) {
            String thumbnailPath = getSdCardCachePath() + File.separator + PICTURE_CACHE;

            size += new FileSize(new File(thumbnailPath)).getLongSize();


        }
        return FileSize.convertSizeToString(size);
    }

    public static boolean deleteCache() {
        String path = getSdCardCachePath() + File.separator;
        return deleteDirectory(new File(path));
    }

    public static boolean deletePictureCache() {
        String thumbnailPath = getSdCardCachePath() + File.separator + PICTURE_CACHE;

        deleteDirectory(new File(thumbnailPath));
//       需要取消图片下载线程

        return true;
    }

    public static boolean deleteDirectory(File path) {
        if (path.exists()) {
            File[] files = path.listFiles();
            if (files == null) {
                return true;
            }
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    deleteDirectory(files[i]);
                } else {
                    files[i].delete();
                }
            }
        }
        return (path.delete());
    }

    public static boolean saveToPicDir(String path) {
        if (!isExternalStorageMounted()) {
            return false;
        }

        File file = new File(path);
        String name = file.getName();
        String newPath = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + ECONTACT
                + File.separator + name;
        try {
            FileManager.createNewFileInSDCard(newPath);
            copyFile(file, new File(newPath));
            Utility.forceRefreshSystemAlbum(newPath);
            return true;
        } catch (IOException e) {
            return false;
        }

    }

    private static void copyFile(File sourceFile, File targetFile) throws IOException {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            outBuff.flush();
        } finally {
            if (inBuff != null) {
                inBuff.close();
            }
            if (outBuff != null) {
                outBuff.close();
            }
        }
    }
}
